import { Component, OnInit, HostListener } from '@angular/core'
import { Observable } from 'rxjs/Observable'
import { Store } from '@ngrx/store'
import * as fromRoot from '../../core/reducers'
import * as fromChecklist from '../../core/actions/checklist'

import { ITask, IUser } from '../../core/models'
import { INewTaskDto, IUpdateTaskDto, IContextTaskDto } from '../../core/dtos'
import { KEY_CODE } from '../../common/keycodes'

@Component({
  selector: 'app-my-day',
  templateUrl: './my-day.component.html',
  styleUrls: [
    './my-day.component.less',
    '../../common/todo-list.less',
    '../../common/new-todo.less']
})
export class MyDayComponent implements OnInit {
  bgurl: string
  newTodo: string
  tasks: ITask[]
  now: string
  focused = false  // 控制添加待办事项的样式
  isDetailDisplayed = false  // 控制右边详情栏是否显示

  currentItem: IContextTaskDto
  contextmenuVisible = false
  contextmenuX = 0
  contextmenuY = 0

  constructor (
    private _store: Store<fromRoot.IState>) { }

  ngOnInit (): void {
    this._store.select(fromRoot.selectTodayTasks).subscribe((tasks) => {
      this.tasks = tasks
      // after addNewTask success, clear newTodo input
      this.newTodo = null
    })
    this.now = this.getDate()
  }

  // 今日任务输入框聚焦与blur
  focus (): void {
    this.focused = true
  }
  blur (): void {
    this.focused = false
  }

  getDate () {
    const date = new Date()
    const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    return `${date.getMonth() + 1}月${date.getDate()}日, ${week[date.getDay()]}`
  }

  // 监听键盘事件（添加待办项目）
  @HostListener('window: keyup', ['$event'])
  keyEvent (event: KeyboardEvent) {
    if (event.keyCode === KEY_CODE.ENTER) {
      this.addNewTask()
    }
  }

  addNewTask () {
    if (this.newTodo && this.newTodo.trim()) {
      const newTask: INewTaskDto = {
        todo: this.newTodo.trim(),
        listId: ''
      }
      this._store.select(fromRoot.selectTodoListId).subscribe(
        (id) => newTask.listId = id
      )
      this._store.dispatch(new fromChecklist.AddTodayTaskAction(newTask))
    }
  }

  // 点击图标toggleDone
  toggleDone (task: ITask, event: MouseEvent) {
    event.stopPropagation()
    const { index, isDone, listId } = task
    const dto: IUpdateTaskDto = {
      listId,
      index,
      ['isDone']: !isDone
    }
    this._store.dispatch(new fromChecklist.ToggleDoneTaskActin(dto))
  }

  changeDetail (task: ITask) {
    this.currentItem = task
  }

  openDetail (task: ITask) {
    this.isDetailDisplayed = true
    this.currentItem = task
  }

  onHideDetail (isHide: boolean) {
    this.isDetailDisplayed = !isHide
  }

  handleContextmenu (e: MouseEvent, item: ITask) {
    this.currentItem = item
    this.contextmenuVisible = true
    this.contextmenuX = e.clientX
    this.contextmenuY = e.clientY
    e.preventDefault()
  }

  @HostListener('document:click') closeContextmenu () {
    this.contextmenuVisible = false
  }

}
